package com.iqiao.platform.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iqiao.common.web.Constant;
import com.iqiao.platform.dao.AdminDao;
import com.iqiao.platform.enums.PlatformType;
import com.iqiao.platform.model.Admin;
import com.iqiao.platform.model.User;
import com.iqiao.platform.service.AdminService;
import com.iqiao.platform.service.RoleService;
import com.iqiao.platform.service.UserService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by flt on 2017/11/13.
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    @Transactional(readOnly = true)
    public PageInfo<Admin> findPage(Map<String, Object> params) {
        int pageNo = MapUtils.getIntValue(params, "pageNo", Constant.PAGE_NO);
        int pageSize = MapUtils.getIntValue(params, "pageSize", Constant.PAGE_SIZE);
        return this.findPage(pageNo, pageSize, params);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<Admin> findPage(int pageNo, int pageSize, Map<String, Object> params) {
        PageHelper.startPage(pageNo, pageSize);
        List<Admin> adminList = adminDao.findAll(params);
        return new PageInfo<Admin>(adminList);
    }

    @Override
    @Transactional
    public Long save(Admin admin) {
        // 密码加密
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));

        // 保存用户信息
        User user = new User();
        user.setNikename(admin.getNikename());
        user.setUsername(admin.getUsername());
        user.setPassword(admin.getPassword());
        user.setScope(PlatformType.ADMIN);
        Long userId = userService.save(user);

        // 设置基本表用户id
        admin.setUserId(userId);
        adminDao.save(admin);
        return admin.getId();
    }

    @Override
    @Transactional(readOnly = true)
    public Admin findByUserId(Long userId) {
        return adminDao.findByUserId(userId);
    }
}
